<template>
  <div>
    <!-- :fetchapi="getLabour"
      :params="fetchParamsLabour"
      :datakey="'rows'"
      :onSyncTableData="columns => (this.allColumns = columns)" -->
    <FilterTable
      ref="tableLabour"
      :columns="columnsLabour"
      columnsRef="closeAssignModelTableLabour"
      :dataSource="labourTableDataSource"
      :isSelectColumn="false"
      :isToperInfo="false"
      :onCellChange="changeColums"
      selectionType="single"
      height="auto"
      :onRowSelectChange="columns => (this.selectColumns = columns)"
      :onColumnsChange="columns => (this.columnsLabour = columns)"
      :onSyncTableData="handleSyncLaoburTableData"
    />
    <FilterTable
      ref="tableHour"
      :columns="columnsHour"
      :fetchapi="getHour"
      columnsRef="closeAssignModelTable"
      :isToperInfo="false"
      :params="fetchParamsHour"
      :isSelectColumn="false"
      :datakey="'rows'"
      :onColumnsChange="columns => (this.columnsHour = columns)"
      :onSyncTableData="columns => (this.allColumnsHour = columns)"
    />
    <!-- <BaseDialog :visible.sync="completed" :title="'竣工'" destroyOnClose width="470px" :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <completedModel :Mileage="this.roNo" @close="closeDialog" />
    </BaseDialog> -->

    <BaseDialog :visible.sync="itemTimes" :title="'工时分配明细'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <itemTimesModel :id="partColumns" @close="closeDialog" />
    </BaseDialog>

    <div style="text-align:center;" class="dialogBottmView">
      <AjaxButton size="small" type="primary" :click="saveDialogAndCompleted">保存及竣工</AjaxButton>
      <AjaxButton size="small" type="primary" :click="saveDialogAndInfo">保存</AjaxButton>
      <el-button size="small" type="primary" @click="closePage">取消</el-button>
    </div>
  </div>
</template>

<script>
import {
  queryRoLabourByRoNOs,
  queryRoAssignByRoNO,
  maintainComplish,
  queryFinished,
  selectWorkGroupDicts,
  maintainComplishNew,
  maintainRepairNew,
  queryRoLabourByRoNOsNoPage
} from '@/api/repair/repairAssign/repairAssign';
import itemTimesModel from './itemTimesModel';
import { dictionary } from '@/utils/dictMixin';
import completedModel from './completedModel';
import moment from 'moment';
import { getShouFeiQuFenSelect } from '@/api/part/partOutbound/repairMaterials/dict.js';
import dictCode from '@/utils/dictCode';
import { searchRoleByCode, searchRoleByCodes } from '@/api/common/empSelect/index';
import { authority } from '@/utils/authMixin';
import { formatdate } from '@/utils/index';

export default {
  name: 'closeAssignModel',
  components: {
    itemTimesModel,
    completedModel
  },
  mixins: [dictionary, authority],
  props: ['roNo', 'tiaoZheng'],
  data() {
    this.BaseTable = null;
    return {
      save: true,
      fetchParamsLabour: {},
      fetchParamsHour: {},
      itemTimes: false,
      completed: false,
      isTrue: false,
      partColumns: {},
      selectColumns: [],
      allColumns: [],
      allColumnsHour: [],
      columnsLabour: this.createTableColumnsLabour(),
      columnsHour: this.createTableColumnsHour(),
      labourTableDataSource: [] // 项目table数据源
    };
  },
  mounted() {
    if (this.tiaoZheng == 'wanGong') {
      this.save = false;
    }
    this.BaseTable = this.$refs.tableLabour.$refs.pageTable;
    this.serviceConsultant();
    this.queryLi(); // 工位
    this.initQueryTableData();
  },
  methods: {
    createTableColumnsLabour() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '是否完工',
          dataIndex: 'FINISHED_TAG',
          sorter: true,
          editable: true,
          editType: 'checkbox',
          defaultEditable: true,
          editItems: [
            { text: '', trueValue: 10041001 },
            { text: '', falseValue: 10041002 }
          ]
        },
        {
          title: '完工时间',
          dataIndex: 'ITEM_END_TIME',
          width: 150,
          sorter: true,
          filter: true,
          editable: true,
          minDateTime: formatdate(new Date(), 1),
          defaultEditable: true,
          editType: 'date-picker',
          dateFormat: 'yyyy-MM-dd HH:mm:ss'
        },
        {
          title: '是否委外',
          dataIndex: 'CONSIGN_EXTERIOR',
          sorter: true,
          filter: true,
          editType: 'select',
          editItems: this.createDictList('1004')
        },
        // {
        //   title: '是否内返',
        //   dataIndex: 'INTER_RETURN',
        //   sorter: true,
        //   filter: true,
        //   editable: true,
        //   editType: 'select',
        //   editItems: this.createDictList('1004')
        // },
        // {
        //   title: '检查结果',
        //   dataIndex: 'TROUBLE_DESC',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input'
        // },
        {
          title: '故障原因',
          dataIndex: 'TROUBLE_CAUSE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '维修项目代码',
          dataIndex: 'LABOUR_CODE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '维修项目名称',
          dataIndex: 'LABOUR_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '收费区分',
          dataIndex: 'CHARGE_PARTITION_CODE',
          sorter: true,
          filter: true,
          editType: 'select',
          editable: false,
          editItems: []
        },
        {
          title: '工时费',
          dataIndex: 'LABOUR_AMOUNT',
          sorter: true,
          filter: true,
          filterType: 'input',
          precision: 2
        },
        {
          title: '派工工时',
          dataIndex: 'ASSIGN_LABOUR_HOUR',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '责任技师',
          dataIndex: 'TECHNICIAN',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: false,
          defaultEditable: true,
          editType: 'select',
          editItems: []
        },
        {
          title: '工位',
          dataIndex: 'LABOUR_POSITION_CODE',
          sorter: true,
          filter: true,
          width: 130,
          editable: true,
          editType: 'select',
          editItems: []
          // editable: true,
          // editType: 'select',
          // editItems: this.createDictList('8004')
        },
        {
          title: '分派工时',
          dataIndex: 'ASSIGN_LABOUR_HOUR_PARTS',
          sorter: true,
          filter: true,
          editable: true,
          editType: 'input'
        },
        {
          title: '检验人',
          dataIndex: 'CHECKER',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: false,
          defaultEditable: true,
          editType: 'select',
          editItems: []
        },
        {
          title: 'flg',
          dataIndex: 'flg',
          sorter: true,
          filter: true,
          filterType: 'input',
          hidden: true
        },
        {
          title: '工时系数(%)',
          dataIndex: 'LABOUR_FACTOR',
          sorter: true,
          filter: true,
          filterType: 'input',
          render: props => {
            return <span>{(props.row.LABOUR_FACTOR * 100).toFixed(0)}</span>;
          }
        },
        // {
        //   title: '工种',
        //   dataIndex: 'WORKER_TYPE_CODE',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   render: props => {
        //     return <span>{this.createDictText(props.row.WORKER_TYPE_CODE, '8041')}</span>;
        //   }
        // },
        {
          title: '开工时间',
          dataIndex: 'ITEM_START_TIME',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },
    createTableColumnsHour() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '维修项目名称',
          dataIndex: 'LABOUR_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '技师',
          dataIndex: 'TECHNICIAN',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: false,
          defaultEditable: true,
          editType: 'select',
          editItems: []
        },
        {
          title: '派工工时',
          dataIndex: 'ASSIGN_LABOUR_HOUR',
          sorter: true,
          filter: true,
          width: 110,
          filterType: 'input'
        },
        {
          title: '实际工作工时',
          dataIndex: 'FACT_LABOUR_HOUR',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '操作',
          dataIndex: ' ',
          render: props => {
            return (
              <el-button icon="el-icon-edit" type="primary" onClick={() => this.itemTimesClick(props)}>
                {}
              </el-button>
            );
          }
        }
      ];
    },
    async queryLi() {
      // 工位
      const sfqfRes = await selectWorkGroupDicts();
      console.log(sfqfRes.data);
      this.columnsLabour.find(item => item.dataIndex === 'LABOUR_POSITION_CODE').editItems = sfqfRes.data.map(x => ({ text: x.LABOUR_POSITION_NAME, value: x.LABOUR_POSITION_CODE }));
    },
    changeColums(a, b) {
      const targetKey = Object.keys(a)[0].split('|')[1];
      if (targetKey === 'FINISHED_TAG') {
        const val = Object.values(a)[0] === '10041002' ? true : false;
        this.BaseTable.SET_CELL_DISABLED(b, 'ITEM_END_TIME', val);
        this.BaseTable.SET_CELL_DISABLED(b, 'CHECKER', val);
        if (b.FINISHED_TAG == '10041001') {
          b.ITEM_END_TIME = moment().format('YYYY-MM-DD');
        } else {
          b.ITEM_END_TIME = '';
          b.CHECKER = '';
        }
      }
      b.flg = 'U';
      this.allColumnsHour.forEach(x => {
        if (x.ITEM_ID == b.ITEM_ID) {
          x.ASSIGN_LABOUR_HOUR = b.ASSIGN_LABOUR_HOUR;
        }
      });
    },
    async serviceConsultant() {
      let technician = { role: dictCode.TECHNICIAN }; // 技师
      let Inspector = { role: dictCode.EXAMINATION_CLERK }; // 检验员

      let technicians = await searchRoleByCodes(technician);
      let Inspectors = await searchRoleByCode(Inspector);
      console.log('检验员', Inspectors);
      if (technicians.resultCode == 200) {
        this.columnsLabour.find(item => item.dataIndex === 'TECHNICIAN').editItems = technicians.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
        this.columnsHour.find(item => item.dataIndex === 'TECHNICIAN').editItems = technicians.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
      } else {
        console.log('技师没有数据');
      }
      if (Inspectors.resultCode == 200) {
        this.columnsLabour.find(item => item.dataIndex === 'CHECKER').editItems = Inspectors.data.map(x => ({ text: x.employeeName, value: x.userId + '' }));
      } else {
        console.log('检验员没有数据');
      }

      // 收费区分
      const sfqfRes = await getShouFeiQuFenSelect();
      this.columnsLabour.find(item => item.dataIndex === 'CHARGE_PARTITION_CODE').editItems = sfqfRes.data.map(x => ({ text: x['CHARGE_PARTITION_NAME'], value: x['CHARGE_PARTITION_CODE'] }));
    },
    // 初始化查询table数据
    async initQueryTableData() {
      this.$refs.tableLabour.START_LOADING();
      try {
        let res = await queryRoLabourByRoNOsNoPage(this.roNo[0].RO_NO);
        if (res.resultCode == 200) {
          res.data.forEach(item => {
            item.FINISHED_TAG == 10041001 && (item.isDisabled = true);
          });
          this.labourTableDataSource = res.data;
        }
      } catch (err) {
        console.log(err, '查询table失败');
      } finally {
        this.$refs.tableLabour.STOP_LOADING();
      }
    },
    // 同步维修项目table数据
    handleSyncLaoburTableData(list) {
      list.forEach(item => {
        item.isDisabled && this.$refs.tableLabour.SET_CELL_DISABLED(item, 'FINISHED_TAG', true);
        item.isDisabled && this.$refs.tableLabour.SET_CELL_DISABLED(item, 'ITEM_END_TIME', true);
        // item.FINISHED_TAG == 10041001 && this.$refs.tableLabour.SET_CELL_DISABLED(item, 'ITEM_END_TIME', true);
      });
      this.allColumns = list;
    },
    async getLabour() {
      return await queryRoLabourByRoNOs(this.roNo[0].RO_NO);
    },
    async getHour() {
      return await queryRoAssignByRoNO(this.roNo[0].RO_NO);
    },
    itemTimesClick(props) {
      this.partColumns = props.row;
      this.itemTimes = true;
    },
    async saveDialogAndCompleted() {
      let resAssign = await queryFinished(this.roNo[0].RO_NO).then(resAssign => {
        if (resAssign.data == '1') {
          this.isTrue = false;
          this.$notify.error({ title: '提示信息', message: '此工单存在未入账配件，不能竣工 !' });
        } else {
          if (this.roNo[0].ASSIGN_STATUS == 80591003) {
            this.saveDialog('isSaveAndCommit'); // 保存及竣工时直接使用单独字段区分
            // .then(async () => {
            //   if (this.isTrue) {
            //     // 竣工重构
            //     let res = await maintainRepairNew({ roNo: this.roNo[0].RO_NO });
            //     this.$emit('close', true);
            //   }
            // });
          } else {
            this.$notify.error({ title: '提示信息', message: '存在未派工的项目，不能竣工 !' });
          }
        }
      });
    },
    async saveDialog(isSaveAndCommit) {
      let obj = {
        roNo: this.roNo[0].RO_NO,
        tables: this.allColumns
      };
      let res = await maintainComplishNew({ ...obj, isSaveAndCommit });
      if (res.resultCode == 200) {
        this.isTrue = true;
        isSaveAndCommit && this.$emit('close', true);
        return Promise.resolve(res);
      }
    },
    async saveDialogAndInfo() {
      // 保存前校验是否有勾选完工
      let targetList = this.allColumns.filter(item => !item.isDisabled);
      let flag = !!targetList.find(item => item.FINISHED_TAG == 10041001);
      if (!flag) return this.$notify.warning({ title: '提示信息', message: '请至少完工一条项目' });

      let res = await this.saveDialog();
      console.log(res, 'hexj001');
      if (res && res.resultCode == 200) {
        this.$notify.success({ title: '提示信息', message: '完工验收成功' });
        this.$emit('close');
      }
    },
    closeDialog(val) {
      if (!val) {
        this.fetchParamsHour = Object.assign({}, this.fetchParams);
      }
      this.itemTimes = false;
      this.completed = false;
    },
    closePage() {
      this.$emit('close');
    }
  }
};
</script>
